export function getWebviewContent(nonce: string, d3Uri: string): string {
    return `<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Code Spider</title>
            <script nonce="${nonce}" src="${d3Uri}"></script>
            <style>
                body, html, svg {
                    margin: 0;
                    padding: 0;
                    width: 100%;
                    height: 100%;
                    overflow: hidden;
                    background-color: rgb(40, 42, 54);
                    color: #f8f8f2;
                }
                .link {
                    stroke: #f8f8f2;
                    stroke-opacity: 0.4;
                }
                .node circle {
                    stroke: #f8f8f2;
                    stroke-width: 1.5px;
                    filter: drop-shadow(0 0 3px rgba(94, 229, 235, 0.7));
                }
                .node.entry circle {
                    fill: #50fa7b; /* Green */
                }
                .node.parent circle {
                    fill: #8be9fd; /* Cyan */
                }
                .node.child circle {
                    fill: #ff79c6; /* Pink */
                }
                .node.large circle {
                    stroke: #f1fa8c; /* Yellow */
                    stroke-width: 4px;
                }
                .node.failed circle {
                    stroke: #ff5555; /* Red */
                    stroke-width: 4px;
                    fill: #6272a4;
                }
                .node.in-cycle circle {
                    stroke: #ffb86c; /* Orange */
                    stroke-width: 4px;
                }
                .link.in-cycle {
                    stroke: #ffb86c; /* Orange */
                    stroke-opacity: 1;
                    stroke-width: 2px;
                }
                .node-label {
                    font: 12px 'Segoe UI', sans-serif;
                    fill: #f8f8f2;
                    pointer-events: none;
                }
                .legend {
                    position: absolute;
                    top: 10px;
                    left: 10px;
                    background: rgba(68, 71, 90, 0.8); /* Darker background */
                    padding: 10px;
                    border-radius: 5px;
                    font-family: 'Segoe UI', sans-serif;
                    font-size: 12px;
                    border: 1px solid #6272a4;
                }
                .legend-item {
                    display: flex;
                    align-items: center;
                    margin-bottom: 5px;
                }
                .legend-color {
                    width: 15px;
                    height: 15px;
                    border-radius: 50%;
                    margin-right: 10px;
                    flex-shrink: 0;
                    box-sizing: border-box;
                }
                .legend-color.large-border {
                    border: 3px solid #f1fa8c; /* Yellow */
                }
                .tooltip {
                    position: absolute;
                    background: rgba(80, 80, 90, 0.9);
                    padding: 8px;
                    border-radius: 4px;
                    font-family: 'Segoe UI', sans-serif;
                    font-size: 12px;
                    border: 1px solid #bd93f9; /* Purple */
                    pointer-events: none; /* Allows clicks to pass through to the SVG */
                    display: none;
                    color: #f8f8f2;
                }
                .tooltip button {
                    pointer-events: all; /* Make buttons clickable */
                    background-color: #bd93f9;
                    border: none;
                    color: #f8f8f2;
                    padding: 4px 8px;
                    text-align: center;
                    text-decoration: none;
                    display: inline-block;
                    font-size: 12px;
                    margin-top: 5px;
                    cursor: pointer;
                    border-radius: 3px;
                }
                .tooltip pre {
                    background-color: #282a36;
                    padding: 5px;
                    border-radius: 3px;
                    white-space: pre-wrap;
                    word-wrap: break-word;
                    max-height: 200px;
                    overflow-y: auto;
                    font-family: 'Fira Code', 'Courier New', monospace;
                    font-size: 11px;
                }
                .search-container {
                    position: absolute;
                    top: 10px;
                    right: 10px;
                }
                .search-container input {
                    width: 200px;
                    padding: 5px;
                    background-color: #282a36;
                    border: 1px solid #6272a4;
                    color: #f8f8f2;
                    border-radius: 4px;
                }
            </style>
        </head>
        <body>
            <div class="search-container">
                <input type="text" id="search-box" placeholder="Search nodes...">
            </div>
             <div class="legend">
                 <div class="legend-item">
                    <div class="legend-color" style="background-color: #50fa7b;"></div>
                    <span>Entry Point</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #8be9fd;"></div>
                    <span>Parents (Depends on Entry)</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #ff79c6;"></div>
                    <span>Children (Entry Depends On)</span>
                </div>
                 <div class="legend-item">
                    <div class="legend-color large-border"></div>
                    <span>Large Component</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="background-color: #6272a4; border: 3px solid #ff5555;"></div>
                    <span>Analysis Failed</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color" style="border: 3px solid #ffb86c;"></div>
                    <span>Circular Dependency</span>
                </div>
            </div>
            <div id="tooltip" class="tooltip"></div>
            <svg></svg>
            <script nonce="${nonce}">
                (function() {
                    const vscode = acquireVsCodeApi();
                    const tooltip = d3.select("#tooltip");
                    const searchBox = document.getElementById('search-box');
                    let simulation;

                    function escapeHtml(text) {
                        if (typeof text !== 'string') return '';
                        return text
                            .replace(/&/g, "&amp;")
                            .replace(/</g, "&lt;")
                            .replace(/>/g, "&gt;")
                            .replace(/"/g, "&quot;")
                            .replace(/'/g, "&#039;");
                    }

                    function renderGraph(data) {
                        try {
                            if (data.nodes && data.links && data.nodes.length > 0) {
                                vscode.postMessage({ command: 'webviewLog', message: 'Render started.' });

                                const svg = d3.select("svg");
                                svg.selectAll("*").remove();
                                
                                const width = window.innerWidth;
                                const height = window.innerHeight;
                                
                                const zoomContainer = svg.append("g");

                                const zoom = d3.zoom()
                                    .scaleExtent([0.1, 4])
                                    .on("zoom", (event) => {
                                        zoomContainer.attr("transform", event.transform);
                                    });
                                svg.call(zoom);

                                simulation = d3.forceSimulation(data.nodes)
                                    .force("link", d3.forceLink(data.links).id(d => d.id).distance(200).strength(0.5))
                                    .force("charge", d3.forceManyBody().strength(-1600))
                                    .force("x", d3.forceX(width / 2).strength(0.1))
                                    .force("y", d3.forceY(height / 2).strength(0.1))
                                    .force("collide", d3.forceCollide().radius(90));

                                const link = zoomContainer.append("g")
                                    .attr("class", "links")
                                    .selectAll("line")
                                    .data(data.links)
                                    .enter().append("line")
                                    .attr("class", d => "link" + (d.inCycle ? " in-cycle" : ""));

                                const node = zoomContainer.append("g")
                                    .attr("class", "nodes")
                                    .selectAll("g")
                                    .data(data.nodes)
                                    .enter().append("g")
                                    .attr("class", d => "node " + d.type + (d.isLarge ? " large" : "") + (d.parseFailed ? " failed" : "") + (d.inCycle ? " in-cycle" : ""))
                                    .on("click", click)
                                    .on("mouseover", mouseover)
                                    .on("mouseout", mouseout)
                                    .call(d3.drag()
                                        .on("start", dragstarted)
                                        .on("drag", dragged)
                                        .on("end", dragended));
                                
                                node.append("circle").attr("r", 10);

                                node.append("text")
                                    .text(d => d.name)
                                    .attr("x", 15)
                                    .attr("y", 5)
                                    .attr("class", "node-label");

                                simulation.on("tick", () => {
                                    link
                                        .attr("x1", d => d.source.x)
                                        .attr("y1", d => d.source.y)
                                        .attr("x2", d => d.target.x)
                                        .attr("y2", d => d.target.y);
                                    node.attr("transform", d => \`translate(\${d.x},\${d.y})\`);
                                });

                                searchBox.addEventListener('input', (e) => {
                                    const searchTerm = e.target.value.toLowerCase();
                                    if (searchTerm.trim() === '') {
                                        node.style("opacity", 1);
                                        link.style("opacity", 1);
                                        return;
                                    }

                                    const matchedNodes = new Set();
                                    data.nodes.forEach(n => {
                                        if (n.name.toLowerCase().includes(searchTerm)) {
                                            matchedNodes.add(n.id);
                                        }
                                    });

                                    node.style("opacity", d => matchedNodes.has(d.id) ? 1 : 0.1);
                                    link.style("opacity", d => (matchedNodes.has(d.source.id) && matchedNodes.has(d.target.id)) ? 1 : 0.05);
                                });
                            } else {
                                const svg = d3.select("svg");
                                svg.selectAll("*").remove();
                                svg.append("text")
                                   .attr("x", "50%")
                                   .attr("y", "50%")
                                   .attr("text-anchor", "middle")
                                   .style("fill", "#f8f8f2")
                                   .style("font-size", "16px")
                                   .text("No nodes or links to render.");
                                vscode.postMessage({ command: 'webviewLog', message: 'No data to render.' });
                            }
                        } catch (error) {
                            vscode.postMessage({ command: 'webviewError', error: { message: error.message, stack: error.stack } });
                        }
                    }
                    
                    function click(event, d) {
                        if (d.isMissing) {
                            vscode.postMessage({ command: 'webviewLog', message: \`Cannot open missing file: \${d.id}\` });
                            return;
                        }
                        vscode.postMessage({ command: 'openFile', path: d.path });
                    }

                    function mouseover(event, d) {
                        const detailsHtml = \`
                            <div><strong>File:</strong> \${escapeHtml(d.name)}</div>
                            <div><strong>Path:</strong> \${escapeHtml(d.path)}</div>
                            <div><strong>Lines:</strong> \${d.lineCount}</div>
                            <div><strong>Depends On:</strong> \${d.dependencyCount} files</div>
                            <div><strong>Referenced By:</strong> \${d.referencedByCount} files</div>
                            \${d.codePreview ? \`<hr><strong>Code Preview:</strong><pre><code>\${escapeHtml(d.codePreview)}</code></pre>\` : ''}
                        \`;

                        tooltip.style("display", "block")
                            .html(detailsHtml)
                            .style("left", (event.pageX + 15) + "px")
                            .style("top", (event.pageY - 28) + "px");
                    }

                    function mouseout(event, d) {
                        tooltip.style("display", "none");
                    }

                    function dragstarted(event, d) {
                        if (!event.active) simulation.alphaTarget(0.3).restart();
                        d.fx = d.x;
                        d.fy = d.y;
                    }

                    function dragged(event, d) {
                        d.fx = event.x;
                        d.fy = event.y;
                    }

                    function dragended(event, d) {
                        if (!event.active) simulation.alphaTarget(0);
                        d.fx = null;
                        d.fy = null;
                    }

                    window.addEventListener('message', event => {
                        const message = event.data;
                        renderGraph(message);
                    });

                    // Initial render with empty data
                    renderGraph({nodes:[], links:[]});
                }());
            </script>
        </body>
        </html>`;
}